import { Component, OnInit, ViewChild} from '@angular/core';
import { AnnexClass } from './annex-class';
import { TipService, ModalTipService, ModalService ,HttpService} from 'itcloud-plugin';
import { Route, Router, ActivatedRoute, Params } from '@angular/router';
import { GetPathService } from '../get-path.service';
import { AddSendeeComponent } from './add-sendee/add-sendee.component';

@Component({
  selector: 'app-add-notice',
  templateUrl: './add-notice.component.html',
  styleUrls: ['./add-notice.component.css']
})
export class AddNoticeComponent implements OnInit {
  data;
  handler;            //来自父组件的数据，和方法；
  // 附件
  annex: AnnexClass[] = [];

  options = {
    url: this.GetPathService.AjaxPath.bulletinServer+'/attachment/addFile',
    method: 'POST',
    itemAlias: 'file',
    autoUpload: true
  };
  fileName: any;
  content: string;      //内容； 
  title:string;         //主题；
  type=0;               //公告通知：0为公告通知；1为信息交流
  message=1;            //短信通知：0为是；1为否；  
  infoStatus=null;      //公告是否打开，只在编辑公告时发送；
  infoCode=null;        //编辑公告时传
  isIntroduced=null;    //编辑公告时传     
  
  startDate= Date.now(); //开启时间默认；                
  endDate;  //关闭时间明天；=Date.now()+24*60*60*1000
  //开启时间选项；
  startDataOptions = {
    minDate: new Date(Date.now()-24*60*60*1000), // Minimal selectable date
    maxDate: new Date('2099/05/31'), // Maximal selectable date
    width: '55%'
  };
  //关闭时间选项；
  endDataOptions = {
    minDate: new Date(this.startDate+24*60*60*1000), // Minimal selectable date
    maxDate: new Date('2099/05/31'), // Maximal selectable date
    width: '55%'
  };
  //tablenew 表格；
    // 表头数据
    headerConfig: Array<any> = [];
    // 表内容数据
    tableData: Array<any> = [];  //所展示的列表内容；
    tableDataAll: Array<any> = [];  //说有的的列表内容上传用；
    addTableData: Array<any> = [];  //新增列表内容；
    delTableId: Array<any> = [];  //删除列表内容的id；

    tableOption: any = {
      // minHeight: '450px',
      checkbox: false,
      multiple: true,
      loading: false
    };

    //分页功能；
    pager3 = {
      total: 0,
      limit: 5,
      page: 1,
      // pageSize:5,
      // pageNum:0
    };
    
    limit={field:5,value:5};
    limitData=[{field:5,value:5},{field:10,value:10},{field:15,value:15},{field:20,value:20}];
    @ViewChild('dcpagination') dcPagination;

  constructor(private http: HttpService,
              private tipService: TipService,
              private GetPathService: GetPathService,
              private modal: ModalService,
              private router: Router,) { }

  ngOnInit() {
    this.setListHeader(); //初始化表头；    

    if(this.data){
      this.init()
    }
  
  }
//点击radio 单选；
  gettype(e){
    if(e.target.defaultValue=='公告通知'){
      this.type=0;
    }else{
      this.type=1;
    }
    console.log(this.type);
  }
  getmess(e){
    if(e.target.defaultValue=='是'){
      this.message=0;
    }else{
      this.message=1;
    }
    console.log(this.message);
  }
//创建公告初始化
init(){

  this.http.getData({
    url: this.GetPathService.AjaxPath.bulletinServer+'/bulletin/getInfoListById',
    search: {id: this.data.id},
  }).subscribe(res => {
    this.title=res['beans'].infoList.infoName;
    this.content=res['beans'].infoList.infoContent;
    this.type=res['beans'].infoList.infoType;
    this.message=res['beans'].infoList.isSms;
    this.infoStatus=res['beans'].infoList.infoStatus;
    this.infoCode=res['beans'].infoList.infoCode;
    this.isIntroduced=res['beans'].infoList.isIntroduced;

  setTimeout(() => {
    this.startDate=res['beans'].infoList.openTime;
    // this.endDate=res['beans'].infoList.closeTime;
  }, );
  setTimeout(() => {
    this.endDate=res['beans'].infoList.closeTime;
  }, 500);

    this.getDemandDetail(res);
    this.getList(res) 
  }, err => { });
}

   /**
   * 获取详细信息做附件编辑回填
   */
  getDemandDetail(res) {
     const arr = res['beans'].from;
     
     for(let i=0;i<arr.length;i++){
      const uoloadDate: AnnexClass = {
      attachName: arr[i].fileName,
      attachUrl: arr[i].filePath,
      attachSize: arr[i].fileSize,
      id: arr[i].id
    }
    this.annex.push(uoloadDate);
     }
  };

  /**
   * 修改上传文件回调
   * @param data
   */
  fileChangeEvent(data) {
    this.fileName = data['file'].name;
  }
  /**
   * 文件上传成功回调
   * @param data
   */
  fileUploadSuccess(res) {
    const data = JSON.parse(res.response);
    data['result'].fileOriginName = this.fileName;

    const uoloadDate: AnnexClass = {
      attachName: data['result'].fileOriginName,
      attachUrl: data['result'].filePath,
      attachSize: data['result'].size,
      id: data['result'].id
    }
    this.annex.push(uoloadDate);
    this.tipService.show({ type: 'success', title: '上传成功！' });
  }

  /**
   * 文件上传失败回调
   * @param data
   */
  fileUploadError(ev) {
    console.log(ev);
    if (ev === 'overSize') {
      this.tipService.show({
        type: 'error',
        title: '上传文件超出最大限制！'
      });
    } else if (ev === 'errorType') {
      this.tipService.show({
        type: 'error',
        title: '上传文件格式不支持！'
      });
    } else {
      this.tipService.show({
        type: 'error',
        title: '上传文件失败！'
      });
    }
  }
  /*
  * 删除上传附件
  * */
  delFiles(ev, list: Array<any>) {
    console.log(ev,list);
    for (let i = list.length - 1; i >= 0; i--) {
      if (list[i].id === ev) {
        list.splice(i, 1);
        break;
      }
    };
  }
  //选择时间插件
  startDateEvent(ev) {
    console.log('start', ev.date);
    setTimeout(() => {
        this.startDate=ev.date.getTime();
        this.endDate=this.startDate+24*60*60*1000; 
        this.endDataOptions={                     //更新关闭时间的最小时间
          minDate: new Date(this.startDate+24*60*60*1000), 
          maxDate: new Date('2099/05/31'), 
          width: '55%'
        };
        console.log(this.endDataOptions)
    }, );

    console.log(this.startDate);
  }
  endDateEvent(ev){
    console.log('end', ev.date);
    setTimeout(() => {
        this.endDate=ev.date.getTime()
    }, );

    console.log(this.endDate);
  }

    /**
   * 初始化表头
   */
  setListHeader() {
    this.headerConfig = [
      {
        field: 'userName',
        title: '姓名',
        width: '20%',
      }, {
        field: 'phone',
        title: '手机号',
        width: '20%',
      }, {
        field: 'organName',
        title: '组织',
        width: '50%',
      },
      {
        field: 'operation',
        title: '操作',
        width: '10%',
      }
    ];
  };
  //获取接收人列表数据
  getList(res){
      this.tableDataAll=res['beans'].userList;
     
      //计算从tableDataAll数据中 截取当前页数来展示；
      this.tableData=this.tableDataAll.slice( this.pager3.limit*(this.pager3.page-1), this.pager3.limit*(this.pager3.page));
      //总条数；
      this.pager3.total=this.tableDataAll.length

  }
  //删除列表项；
  deleteDemand(dataParam){
       console.log(dataParam.userId);
       for(let i=0; i<this.tableDataAll.length;i++){
        if(this.tableDataAll[i].userId == dataParam.userId){
            this.tableDataAll.splice(i,1)
        }
       }
        //计算从tableDataAll数据中 截取当前页数来展示；
        this.tableData=this.tableDataAll.slice( this.pager3.limit*(this.pager3.page-1), this.pager3.limit*(this.pager3.page));
        //总条数；
        this.pager3.total=this.tableDataAll.length
        if(!this.tableData.length && this.pager3.page >1){   //如果当前页没有数据，页数就减一；
          this.pager3.page--;
          this.tableData=this.tableDataAll.slice( this.pager3.limit*(this.pager3.page-1), this.pager3.limit*(this.pager3.page));
        }

        this.delTableId.push(dataParam.userId);  //添加删除接受人的id
        console.log(this.tableData)
       console.log(this.tableDataAll)
       console.log(this.pager3)
  };
  //改变页数；
  nowPageChange(pageNum) {
       console.log(pageNum);
       this.pager3.page=pageNum;
         //计算从tableDataAll数据中 截取当前页数来展示；
       this.tableData=this.tableDataAll.slice( this.pager3.limit*(this.pager3.page-1), this.pager3.limit*(this.pager3.page));
  };
  //改变limit；
  limitSelect(ev){
        console.log(ev)
        this.pager3.limit=ev.field;
        this.pager3.page=1;
        //更新最大页数；
        this.dcPagination.maxPage=Math.ceil(this.tableDataAll.length / this.pager3.limit);
        //计算从tableDataAll数据中 截取当前页数来展示；
        this.tableData=this.tableDataAll.slice( this.pager3.limit*(this.pager3.page-1), this.pager3.limit*(this.pager3.page));
  }
  addSendeeData(){
    const result = this.modal.open({
      title: '添加接收人',
      component: AddSendeeComponent,
      backdropCloseable: false,
      width: '800px',
      data: 'laofanlaofan',
      handler: (data) => {
        if(data){
          for(let i=0;i<data.length;i++ ){
            for(let j=0;j<this.tableDataAll.length;j++){
              if(data[i].userId == this.tableDataAll[j].userId){
                this.tipService.show({ type: 'error', title: `${data[i].userName}已在接收人列表中，不可重复添加！`});
                return;
              }
            }
          }
        this.addTableData=this.addTableData.concat(data);
        this.tableDataAll=this.tableDataAll.concat(data).reverse();
        console.log(this.tableDataAll,this.tableDataAll.length)
        //计算从tableDataAll数据中 截取当前页数来展示；
        this.tableData=this.tableDataAll.slice( this.pager3.limit*(this.pager3.page-1), this.pager3.limit*(this.pager3.page));
        this.pager3.total=this.tableDataAll.length;
        this.tipService.show({ type: 'success', title: '接收人添加成功！'});
      }
        result.modalInstance.hide();
      }
    });
  };

  getDatas(){
    const userIds=[];                         //所有接受人id
    let  addId='';
    let  deleteId='';
    for(let i=0;i<this.tableDataAll.length;i++){
      userIds.push(this.tableDataAll[i].userId)
    }
    if(this.data){                            //如果是编辑修改就 addid和deleteid 赋值；
      const add=[];
      for(let i=0;i<this.addTableData.length;i++){
        add.push(this.addTableData[i].userId)
      };
      addId =add.join();
      deleteId=this.delTableId.join();
    }
    const uploadId=[];                 //获取上传附件的id；
    for(let i=0;i<this.annex.length;i++){
      uploadId.push(this.annex[i].id)
    }
  
    const param = {
      id: this.data ? this.data.id : null,
      infoStatus: this.infoStatus,
      infoCode: this.infoCode,
      isIntroduced: this.isIntroduced,
      infoName: this.title,
      infoContent: this.content,
      infoType: this.type,
      isSms: this.message,
      openTime: this.startDate,
      closeTime: this.endDate,
      attachmentIds: uploadId.join(),
      createPerson:this.getCookie('userId'),
      updatePerson:this.getCookie('userId'),
      userIds: userIds.join(),
      deleteId: deleteId,
      addId: addId

    };
    return param;
  }
  //保存；
  save(){
    //表单验证；
    if(!this.title ||!this.content ||this.tableDataAll.length==0){
      this.tipService.show({ type: 'error', title: '必填项未填'});
      return;
    }
    this.http.postData({
      url: this.GetPathService.AjaxPath.bulletinServer+'/bulletin/keepBilletin',
      data: this.getDatas(),
    }).subscribe(res => {
      this.tipService.show({ type: 'success', title: res['message']});
      this.router.navigate(['/found']);      //成功后，返回我的创建；
      if(this.data){this.handler()}          //成功后，如果时编辑公告关掉父组件；
      console.log('成功',res);
    }, err => {this.tipService.show({ type: 'error', title: '保存失败'}); console.log('失败',err)});
  }
//发布公告；
  sendNotice(){
    //表单验证；
    if(!this.title ||!this.content ||this.tableDataAll.length==0){
      this.tipService.show({ type: 'error', title: '必填项未填'});
      return;
    }
    this.http.postData({
      url: this.GetPathService.AjaxPath.bulletinServer+'/bulletin/submitBilletin',
      data: this.getDatas(),
    }).subscribe(res => {
      this.tipService.show({ type: 'success', title: res['message']});
      this.router.navigate(['/found']);     //成功后，返回我的创建；
      if(this.data){this.handler()}          //成功后，如果时编辑公告关掉父组件；

    }, err => {this.tipService.show({ type: 'error', title: '发布失败'}); });
  
  }
  //取消按钮；
  cancel(){
    this.router.navigate(['/found']);     //返回我的创建；
    if(this.data)this.handler();          //成功后，如果时编辑公告关掉父组件；
  }
//获取cookie的方法；
  getCookie(name) {
    let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

    if (arr = document.cookie.match(reg))

        return decodeURI(arr[2]);
    else
        return null;
  }

}
